from logger import logger
logger.debug("Loaded mouse event handler module")

import pygame
import state
import cfg

from rabbyt import collisions as coll

def handle(e):
	if e.type == pygame.MOUSEMOTION:
		state.mouse.x, state.mouse.y = e.pos[0], e.pos[1]
		if state.mouse.x < cfg.scrollborder and state.cam.move.x == 0:
			state.cam.move.x = -1
			state.cam.move.mouse = True
		elif state.mouse.x > cfg.resolution[0] - cfg.scrollborder and state.cam.move.x == 0:
			state.cam.move.x = 1
			state.cam.move.mouse = True
		if state.mouse.y < cfg.scrollborder and state.cam.move.y == 0:
			state.cam.move.y = -1
			state.cam.move.mouse = True
		elif state.mouse.y > cfg.resolution[1] - cfg.scrollborder and state.cam.move.y == 0:
			state.cam.move.y = 1
			state.cam.move.mouse = True
		elif (state.mouse.x >= cfg.scrollborder) \
				and (state.mouse.x <= cfg.resolution[0] - cfg.scrollborder) \
				and (state.mouse.y >= cfg.scrollborder) \
				and (state.mouse.y <= cfg.resolution[1] - cfg.scrollborder):
			state.cam.move.mouse = False
	elif e.type == pygame.MOUSEBUTTONDOWN:
		if e.button == 1: # left button - used for selection
			colls = coll.collide_single(state.mouse, state.units)
			if state.selected != None:
				state.selected.selected = False
				state.selected.sprite.alpha = 0.7
				state.selected = None
			if colls != None and colls != []:
				state.selected = colls[0]
				colls[0].selected = True
				colls[0].sprite.alpha = 1.0
		elif e.button == 2: # middle button: anything for this?
			pass
		elif e.button == 3: # right button - movement needs to be implemented
			pass
		elif e.button == 4: # zoom out
			state.cam.zoom = state.cam.zoom / cfg.zoomspeed
			if state.cam.zoom > cfg.maxZoom or state.cam.zoom < cfg.minZoom:
				state.cam.zoom = state.cam.zoom * cfg.zoomspeed

		elif e.button == 5: # zoom in
			state.cam.zoom = state.cam.zoom * cfg.zoomspeed
			if state.cam.zoom < cfg.minZoom or state.cam.zoom > cfg.maxZoom:
				state.cam.zoom = state.cam.zoom / cfg.zoomspeed
		elif e.button == 6: # do nothing for left scroll button (yet :D)
			pass
		elif e.button == 7: # do nothing for right scroll (yet :D)
			pass
		else:
			logger.debug("unknown mouse button pressed: " + str(e.button))

